/**
 * 
 */
package com.jxc.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.Brand;
import com.jxc.model.po.Goods;
import com.jxc.model.po.GoodsRepertory;
import com.jxc.model.po.GoodsType;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.SaleReturnlistItem;
import com.jxc.model.po.Salelist;
import com.jxc.model.po.SalelistItem;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VOrderlistItem;
import com.jxc.model.vo.VSalelistItem;
import com.jxc.service.OrderServiceI;
import com.jxc.service.SalelistItemServiceI;

/**
 * @author Tino
 * 
 */
@Service("salelistItemService")
public class SalelistItemServiceImpl implements SalelistItemServiceI {

	@Autowired
	private BaseDaoI<SalelistItem> salelistItemDao;
	@Autowired
	private BaseDaoI<Salelist> salelistDao;
	@Autowired
	private BaseDaoI<GoodsRepertory> goodsrepertorydao;
	@Autowired
	private BaseDaoI<SaleReturnlistItem> salereturndao;

	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private OrderServiceI orderServiceI; 
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistItemServiceI#batchSave(java.util.List,
	 *      java.lang.Long)
	 */
	@Override
	public void batchSave(List<VSalelistItem> vslis, Long slid) {
		for (VSalelistItem vsli : vslis) {
			vsli.setSlid(slid);
			this.save(vsli);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistItemServiceI#combobox(com.jxc.model.vo.VSalelistItem)
	 */
	@Override
	public List<VSalelistItem> combobox(VSalelistItem vsli) {
		return this.changeModel(this.find(vsli));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistItemServiceI#datagrid(com.jxc.model.vo.VSalelistItem)
	 */
	@Override
	public DataGrid datagrid(VSalelistItem vsli) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vsli)));
		dg.setTotal(this.total(vsli));
		return dg;
	}

	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistItemServiceI#delete(java.lang.String)
	 */
	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					SalelistItem ct = this.salelistItemDao.get(SalelistItem.class, Long.parseLong(id.trim()));
					if (ct != null) {
						this.salelistItemDao.delete(ct);
					}
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistItemServiceI#save(com.jxc.model.vo.VSalelistItem)
	 */
	@Override
	public void save(VSalelistItem vsli) {
		SalelistItem sli = new SalelistItem();
		BeanUtils.copyProperties(vsli, sli);
		if (vsli.getGid() != null) {
			sli.setGoods(new Goods(vsli.getGid()));
		}
		if (vsli.getSlid() != null) {
			sli.setSalelist(salelistDao.get(Salelist.class, vsli.getSlid()));
		}
		this.salelistItemDao.save(sli);
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jxc.service.SalelistItemServiceI#update(com.jxc.model.vo.VSalelistItem)
	 */
	@Override
	public void update(VSalelistItem vsli) {
		SalelistItem sli = this.salelistItemDao.get(SalelistItem.class, vsli.getId());
		BeanUtils.copyProperties(vsli, sli, new String[] { "id" });
		if (vsli.getGid() != null) {
			sli.setGoods(new Goods(vsli.getId()));
		}
		if (vsli.getSlid() != null) {
			sli.setSalelist(new Salelist(vsli.getSlid()));
		}
		this.salelistItemDao.update(sli);
	}


	private List<VSalelistItem> changeModel(List<SalelistItem> slis) {
		List<VSalelistItem> vslis = new ArrayList<VSalelistItem>();
		if (slis != null && slis.size() > 0) {
			for (SalelistItem sli : slis) {
				VSalelistItem vsli = new VSalelistItem();
				BeanUtils.copyProperties(sli, vsli);
				if (sli.getGoods() != null) {
					Goods goods = sli.getGoods();
					vsli.setGid(goods.getId());
					vsli.setGname(goods.getName());
				}
				if (sli.getSalelist() != null) {
					Salelist sl = sli.getSalelist();
					vsli.setSlid(sl.getId());
				}
				vslis.add(vsli);
			}
		}
		return vslis;
	}
	
	public List<VSalelistItem> changeModelAll(List<GoodsRepertory> goodsRepertories){
		List<VSalelistItem> vslis = new ArrayList<VSalelistItem>();
		if (goodsRepertories != null && goodsRepertories.size() > 0) {
			for (GoodsRepertory sli : goodsRepertories) {
				VSalelistItem vsli = new VSalelistItem();
				BeanUtils.copyProperties(sli, vsli);
				if (sli.getGoods() != null) {
					Goods goods = sli.getGoods();
					vsli.setGid(goods.getId());
					vsli.setGname(goods.getName());
					vsli.setGbarcode(goods.getBarcode());
					vsli.setGtype(goods.getType());
					vsli.setBuyPrice(goods.getBuyPrice());
					vsli.setGsize(goods.getSize());
					vsli.setShowPrice(goods.getShowPrice());
					vsli.setGcolor(goods.getColor());
					if(goods.getBrand()!=null){
						Brand bra = goods.getBrand();
						vsli.setBid(bra.getId());
						vsli.setBname(bra.getName());
					}
					if(goods.getGoodsType()!=null){
						GoodsType gt = goods.getGoodsType();
						vsli.setGtid(gt.getId());
						vsli.setGtname(gt.getName());
					}
				}
				if(sli.getRepertory()!=null){
					Repertory re = sli.getRepertory();
					vsli.setRid(re.getId());
					vsli.setRname(re.getName());
				}
				if(vsli.getGid()!=null&&vsli.getRid()!=null){
					String hql1 = "select sum(s.total) from SalelistItem s join s.salelist l where s.goods.id="+vsli.getGid()+"" +
							" and l.repertory.id="+vsli.getRid();//销售金额
					Double xsje = salelistItemDao.count1(hql1);
					String hql3 = "select sum(s.total) from SaleReturnlistItem s join s.saleReturnlist l where s.goods.id="+vsli.getGid()+"" +
							" and l.repertory.id="+vsli.getRid();//销售退货金额
					Double thje = salelistItemDao.count1(hql3);
					
					if(xsje==null)xsje=0d;
					if(thje==null)thje=0d;
					Double xs = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xsje));
					Double th = Double.parseDouble(new java.text.DecimalFormat("#.00").format(thje));
					vsli.setXsje(sub(xs, th));
					String hql2 = "select sum(s.number) from SalelistItem s join s.salelist l where s.goods.id="+vsli.getGid()+"" +
							" and l.repertory.id="+vsli.getRid();//销售数量
					Long xssl = salelistItemDao.count(hql2);
					String hql4 = "select sum(s.num) from SaleReturnlistItem s join s.saleReturnlist l where s.goods.id="+vsli.getGid()+"" +
							" and l.repertory.id="+vsli.getRid();
					Long thsl = salelistItemDao.count(hql4);
					
					if(xssl==null)xssl=new Long(0);
					if(thsl==null)thsl=new Long(0);
					vsli.setZxssl(xssl);
					vsli.setZthsl(thsl);
					vsli.setXssl(xssl-thsl);
				}
				
				vslis.add(vsli);
			}
		}
		return vslis;
	}

	private List<SalelistItem> find(VSalelistItem vsli) {
		String hql = "from SalelistItem t where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vsli, hql, values);

		if (vsli.getSort() != null && vsli.getOrder() != null) {
			hql += " order by " + vsli.getSort() + " " + vsli.getOrder();
		}
		return this.salelistItemDao.find(hql, values, vsli.getPage(), vsli.getRows());
	}

	private Long total(VSalelistItem vsli) {
		String hql = "select count(*) from SalelistItem t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vsli, hql, values);
		return this.salelistItemDao.count(hql, values);
	}

	private String addWhere(VSalelistItem vsli, String hql, List<Object> values) {
		if (vsli.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vsli.getId());
		}

		if (vsli.getGid() != null) {
			hql += " and t.goods.id = ? ";
			values.add(vsli.getGid());
		}
		if (vsli.getSlid() != null) {
			hql += " and t.salelist.id = ? ";
			values.add(vsli.getSlid());
		}
		
		return hql;
	}

	@Override
	public DataGrid datagridAll(VSalelistItem vsli) {
		DataGrid dg = new DataGrid();
		dg.setRows(changeModelAll(this.findAll(vsli)));
		dg.setTotal(totalAll(vsli));
		return dg;
	}

	private List<GoodsRepertory> findAll(VSalelistItem vsli) {
		List<GoodsRepertory> grs = new ArrayList<GoodsRepertory>();
		try{
			String hql = "select t from SalelistItem si join si.salelist s join s.repertory r join r.goodsRepertoryList t "+
				"  left join s.salereturnlists xs where si.salelist.id=s.id " +
				" and s.repertory.id=r.id and t.goods.id=si.goods.id and r.id=t.repertory.id " ;
			List<Object> values = new ArrayList<Object>();
		
			hql = addWhere2(vsli, hql, values);
			hql += " group by t.id";
			if (vsli.getSort() != null && vsli.getOrder() != null&&vsli.getSort()!="name"&&!vsli.getSort().equals("name")) {
				if(vsli.getSort().equals("gbarcode")||vsli.getSort().equals("gtype")||vsli.getSort().equals("gname")||vsli.getSort().equals("gsize")){
					hql += " order by t.goods." + vsli.getSort().substring(1,vsli.getSort().length()) + " " + vsli.getOrder();
				}
				else if(vsli.getSort().equals("showPrice")||vsli.getSort().equals("buyPrice")){
					hql += " order by t.goods." + vsli.getSort()+ " " + vsli.getOrder();
				}
				else if(vsli.getSort().equals("zxssl")){//销售数量
					hql += " order by  sum(si.number) " + vsli.getOrder();
				} 
				else if(vsli.getSort().equals("zthsl")){//退货数量
					hql += " order by  sum(xs.items.num) " + vsli.getOrder();
				}
				else{
					hql += " order by t.goods." + vsli.getSort() + " " + vsli.getOrder();
				}
			}
			grs = goodsrepertorydao.find(hql, values, vsli.getPage(), vsli.getRows());
		}catch(Exception e){
			e.printStackTrace();
		}
		return grs ;
	}

	
	
	private String addWhere2(VSalelistItem vsli, String hql, List<Object> values) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (vsli.getUid() != null) {	
			hql += " and t.repertory.user.id = ? ";
			values.add(vsli.getUid());
		}
		if (vsli.getBid() != null) {
			hql += " and t.goods.brand.id = ? ";
			values.add(vsli.getBid());
		}
		if (vsli.getGtid() != null) {
			hql += " and t.goods.goodsType.id = ? ";
			values.add(vsli.getGtid());
		}
		if (vsli.getRid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vsli.getRid());
		}
		if(vsli.getGbarcode()!=null&&!vsli.getGbarcode().trim().equals("")){
			hql += " and t.goods.barcode like ?";
			values.add("%%"+vsli.getGbarcode()+"%%");
		}
		if(vsli.getGtype()!=null&&!vsli.getGtype().trim().equals("")){
			hql += " and t.goods.type like ?";
			values.add("%%"+vsli.getGtype()+"%%");
		}
		if(vsli.getGcolor()!=null&&!vsli.getGcolor().trim().equals("")){
			hql += " and t.goods.color like ?";
			values.add("%%"+vsli.getGcolor()+"%%");
		}if(vsli.getGsize()!=null&&!vsli.getGsize().trim().equals("")){
			hql += " and t.goods.size like ?";
			values.add("%%"+vsli.getGsize()+"%%");
		}
		if (vsli.getBeginDate() != null) {
			hql += " and s.date >="+"'"+sdf.format(vsli.getBeginDate())+"'";
		}
		if (vsli.getEndDate() != null) {
			hql += " and s.date <= "+"'"+sdf.format(vsli.getEndDate())+"'";
		}
		return hql;
	}
	
	 public static Double sub(Double v1,Double v2){
	        BigDecimal b1 = new BigDecimal(Double.toString(v1));
	        BigDecimal b2 = new BigDecimal(Double.toString(v2));
	        return b1.subtract(b2).doubleValue();
	 }
	 
	 
	 
	private Long totalAll(VSalelistItem vsli) {
		 Long aa = 0l;
		 String hql1 = "";
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
		  hql1 = "select count(*) from "+
					" (select count(*) from xsgl_salelist_item si join xsgl_salelist s join rkgl_repertory r join rkgl_goods_repertory gr join spgl_goods g " +
					" where si.salelist_id=s.id and s.repertory_id=r.id and si.goods_id = g.id  and si.goods_id = g.id and gr.repertory_id=r.id and gr.goods_id=si.goods_id ";
		 	if (vsli.getUid() != null) {
				hql1 += " and r.user_id = "+vsli.getUid();
			}
			if (vsli.getBid() != null) {
				hql1 += " and g.brand_id = "+vsli.getBid();
			}
			if (vsli.getGtid() != null) {
				hql1 += " and g.goods_type_id = "+vsli.getGtid();
			}
			if (vsli.getRid() != null) {
				hql1 += " and r.id = "+vsli.getRid();
			}

			if(vsli.getGbarcode()!=null&&!vsli.getGbarcode().trim().equals("")){
				hql1 += " and g.barcode like "+"'%"+vsli.getGbarcode()+"%'";
			}
			if(vsli.getGtype()!=null&&!vsli.getGtype().trim().equals("")){
				hql1 += " and g.type like "+"'%"+vsli.getGtype()+"%'";
			}
			if(vsli.getGsize()!=null&&!vsli.getGsize().trim().equals("")){
				hql1 += " and g.size like "+"'%"+vsli.getGsize()+"%'";
			}
			if(vsli.getGcolor()!=null&&!vsli.getGcolor().trim().equals("")){
				hql1 += " and t.goods.color like "+"'%"+vsli.getGcolor()+"%'";
			}
			if (vsli.getBeginDate() != null) {
				hql1 += " and s.date >= '"+sdf.format(vsli.getBeginDate())+"'";
			}

			if (vsli.getEndDate() != null) {
				hql1 += " and s.date <= '"+sdf.format(vsli.getEndDate())+"'";
			}
			hql1 += "  group by gr.ID)aa";
			BigInteger a = this.salelistItemDao.countSQL(hql1);
			aa = a.longValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	
     
       return aa;
	       
	}
	
	
	private String addWhere3(VSalelistItem vsli, String hql) {
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (vsli.getUid() != null) {
			hql += " and r.user.id = "+vsli.getUid();
		}
		if (vsli.getBid() != null) {
			hql += " and s.goods.brand.id = "+vsli.getBid();
		}
		if (vsli.getGtid() != null) {
			hql += " and s.goods.goodsType.id ="+vsli.getGtid();
		}
		if (vsli.getRid() != null) {
			hql += " and r.id = "+vsli.getRid();
		}
		if(vsli.getGbarcode()!=null&&!vsli.getGbarcode().trim().equals("")){
			hql += " and s.goods.barcode like "+"'%"+vsli.getGbarcode()+"%'";
		}
		if(vsli.getGtype()!=null&&!vsli.getGtype().trim().equals("")){
			hql += " and s.goods.type like "+"'%"+vsli.getGtype()+"%'";
		}
		if(vsli.getGsize()!=null&&!vsli.getGsize().trim().equals("")){
			hql += " and s.goods.size like "+"'%"+vsli.getGsize()+"%'";
		}
		if (vsli.getBeginDate() != null) {
			hql += " and l.date >= '"+sdf.format(vsli.getBeginDate())+"'";
		}
		if (vsli.getEndDate() != null) {
			hql += " and l.date <= '"+sdf.format(vsli.getEndDate())+"'";
		}
		return hql;
	}

	@Override
	public VSalelistItem findSaleTotal(VSalelistItem vsli) {	
		VSalelistItem vslitem = new VSalelistItem();
		try {
			//销售金额
			String hql1 = "select sum(s.total) from SalelistItem s join s.salelist l join l.repertory r  where "+
					"  r.isDelete = false";
			hql1 = addWhere3(vsli, hql1);
			Double xsje = salelistItemDao.count1(hql1);
			if(xsje==null)xsje=0d;
			Double xs = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xsje));
			if(xs==null)xs=0d; 
			//抹零金额
			String hql2 = "select sum(l.wipeZero) from SalelistItem s join s.salelist l join l.repertory r  where "+
					"  r.isDelete = false";
			hql2 = addWhere3(vsli, hql2);
			Double mlje = salelistItemDao.count1(hql2);
			if(mlje==null)mlje=0d;
			Double ml = Double.parseDouble(new java.text.DecimalFormat("#.00").format(mlje));
			if(ml==null)ml=0d; 
			//退货金额
			String hql3 = "select sum(s.total) from SaleReturnlistItem s join s.saleReturnlist l join l.repertory r  where "+
					"  r.isDelete = false";
			hql3 = addWhere3(vsli, hql3);
			Double thje = salelistItemDao.count1(hql3);
			if(thje==null)thje=0d;
			Double th = Double.parseDouble(new java.text.DecimalFormat("#.00").format(thje));
			if(th==null)th=0d; 
			//实际销售总金额
			Double sjje = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xs-ml-th));
			vslitem.setXszje(sjje);
			//销售数量
			String hql4 = "select sum(s.number) from SalelistItem s join s.salelist l join l.repertory r  where "+
					"  r.isDelete = false";
			hql4 = addWhere3(vsli, hql4);
			Long xssl = salelistItemDao.count(hql4);
			if(xssl==null)xssl=0l;
			//退货数量
			String hql5 = "select sum(s.num) from SaleReturnlistItem s join s.saleReturnlist l join l.repertory r  where "+
					"  r.isDelete = false";
			hql5 = addWhere3(vsli, hql5);
			Long thsl = salelistItemDao.count(hql5);
			if(thsl==null)thsl=0l;
			vslitem.setThzsl(thsl);
			//实际销售总数量 
			vslitem.setXszsl(xssl-thsl);
			//优惠金额
			String hql6 = "select sum(l.viptotal) from SalelistItem s join s.salelist l join l.repertory r  where "+
					"  r.isDelete = false";
			hql6 = addWhere3(vsli, hql6);
			Double yhje = salelistItemDao.count1(hql6);
			if(yhje==null)yhje=0d;
			Double yh = Double.parseDouble(new java.text.DecimalFormat("#.00").format(yhje));
			if(yh==null)yh=0d; 
			//实际优惠金额
			Double shhyje = Double.parseDouble(new java.text.DecimalFormat("#.00").format(yhje+ml));
			vslitem.setYhzje(shhyje);
			
			//销售成本
		    Double cbzje =  this.findXscbBySql(vsli);
		    //退货成本 
		    Double thcb = this.findThcbBySql(vsli);
		   
		    Double xscb = Double.parseDouble(new java.text.DecimalFormat("#.00").format(cbzje));
			if(xscb==null)xscb=0d; 
			vslitem.setCb(xscb);
		 
			if(thcb==null)thcb=0d;
			Double thzcb = Double.parseDouble(new java.text.DecimalFormat("#.00").format(thcb));
			if(thzcb==null)thzcb=0d; 
		    //成本
			Double cb = Double.parseDouble(new java.text.DecimalFormat("#.00").format(xscb-thcb));
		    vslitem.setCb(cb);
			//利润
		    Double lr =  Double.parseDouble(new java.text.DecimalFormat("#.00").format(sjje-xscb));
		    vslitem.setLr(lr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vslitem;
	}
	 
	 private String addWhere3BySql(VSalelistItem vsli, String hql) {
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if (vsli.getUid() != null) {
				hql += " and r.user_id = "+vsli.getUid();
			}
			if (vsli.getBid() != null) {
				hql += " and g.brand_id = "+vsli.getBid();
			}
			if (vsli.getGtid() != null) {
				hql += " and g.goodsType_id ="+vsli.getGtid();
			}
			if (vsli.getRid() != null) {
				hql += " and r.id = "+vsli.getRid();
			}
			if(vsli.getGbarcode()!=null&&!vsli.getGbarcode().trim().equals("")){
				hql += " and g.barcode like "+"'%"+vsli.getGbarcode()+"%'";
			}
			if(vsli.getGtype()!=null&&!vsli.getGtype().trim().equals("")){
				hql += " and g.type like "+"'%"+vsli.getGtype()+"%'";
			}
			if(vsli.getGsize()!=null&&!vsli.getGsize().trim().equals("")){
				hql += " and g.size like "+"'%"+vsli.getGsize()+"%'";
			}
			if (vsli.getBeginDate() != null) {
				hql += " and l.date >= '"+sdf.format(vsli.getBeginDate())+"'";
			}
			if (vsli.getEndDate() != null) {
				hql += " and l.date <= '"+sdf.format(vsli.getEndDate())+"'";
			}
			return hql;
		}

	public Double findThcbBySql(VSalelistItem vg){ 
		 //退货成本总金额
		 //成本总金额
		int kc = 0;
		Double cb = 0d;
	    String hql = "select s.num,s.goods_id,l.repertory_id from xsgl_salereturnlist_item s,xsgl_salereturnlist l," +
	    		" spgl_goods  g,rkgl_repertory r  where s.salereturnlist_id=l.id and s.goods_id=g.id and l.repertory_id=r.id ";
	    hql = addWhere3BySql(vg, hql);
	 	List<Object[]>   grs =  salereturndao.findBySql(hql);
	 	for(Object[] o:grs){
	 		for (int j = 0; j < o.length;j++) {
	 			VGoodsRepertory vr = new VGoodsRepertory();
				vr.setNum(Integer.parseInt(o[j].toString()));//库存
				vr.setGid(Long.parseLong(o[++j].toString()));//商品ID
				vr.setRid(Long.parseLong(o[++j].toString()));//仓库ID
				List<Object[]> vsi = orderServiceI.findByGoods(vr,"");
				if(vsi.size()==0){
					String hs = " select buy_price from spgl_goods where id="+vr.getGid();
					Double bd = goodsDao.countSQL1(hs);
					if(bd==null)bd=0d; 
					cb += vr.getNum()*bd;
				}else{
					List<VOrderlistItem> volis = new ArrayList<VOrderlistItem>();
					for(Object[] vs:vsi){
						for (int i = 0; i < vs.length;i++) {
							VOrderlistItem voli = new VOrderlistItem();
							voli.setNum(Integer.parseInt(vs[i].toString()));
							voli.setBuyPrice(Double.parseDouble(vs[++i].toString()));
							volis.add(voli);
						}
					}
					for (int i = 0; i < volis.size(); ) {
						VOrderlistItem voli = volis.get(i);
			 			if(kc<=0){
			 				kc = vr.getNum();
			 			}
			 			if(kc-voli.getNum()>0){
			 				cb += voli.getNum()*voli.getBuyPrice();
			 				kc = vr.getNum()-voli.getNum();
			 				i++;
			 			}else{
			 				cb += kc*voli.getBuyPrice();
			 				kc = 0;
			 				break;
			 			}
					}
				}
			}
	 	}
		return cb; 
	}
	 
	
	public Double findXscbBySql(VSalelistItem vg){ 
		 //销售成本总金额
		 //成本总金额
		int kc = 0;
		Double cb = 0d;
	    String hql = "select s.number,s.goods_id,l.repertory_id from xsgl_salelist_item s,xsgl_salelist l," +
	    		" spgl_goods  g,rkgl_repertory r  where s.salelist_id=l.id and s.goods_id=g.id and l.repertory_id=r.id ";
	    hql = addWhere3BySql(vg, hql);
	 	List<Object[]>   grs =  salereturndao.findBySql(hql);
	 	for(Object[] o:grs){
	 		for (int j = 0; j < o.length;j++) {
	 			VGoodsRepertory vr = new VGoodsRepertory();
				vr.setNum(Integer.parseInt(o[j].toString()));//库存
				vr.setGid(Long.parseLong(o[++j].toString()));//商品ID
				vr.setRid(Long.parseLong(o[++j].toString()));//仓库ID
				List<Object[]> vsi = orderServiceI.findByGoods(vr,"");
				if(vsi.size()==0){
					String hs = " select buy_price from spgl_goods where id="+vr.getGid();
					Double bd = goodsDao.countSQL1(hs);
					if(bd==null)bd=0d; 
					cb += vr.getNum()*bd;
				}else{
					List<VOrderlistItem> volis = new ArrayList<VOrderlistItem>();
					for(Object[] vs:vsi){
						for (int i = 0; i < vs.length;i++) {
							VOrderlistItem voli = new VOrderlistItem();
							voli.setNum(Integer.parseInt(vs[i].toString()));
							voli.setBuyPrice(Double.parseDouble(vs[++i].toString()));
							volis.add(voli);
						}
					}
					for (int i = 0; i < volis.size(); ) {
						VOrderlistItem voli = volis.get(i);
			 			if(kc<=0){
			 				kc = vr.getNum();
			 			}
			 			if(kc-voli.getNum()>0){
			 				cb += voli.getNum()*voli.getBuyPrice();
			 				kc = vr.getNum()-voli.getNum();
			 				i++;
			 			}else{
			 				cb += kc*voli.getBuyPrice();
			 				kc = 0;
			 				break;
			 			}
					}
				}
			}
	 	}
		return cb; 
	}
	 
	/* public Double findXscb(VSalelistItem vg ){ 
		int kc = 0;
		Double cb = 0d;
		String hql = "select s from SalelistItem s join s.salelist l join l.repertory r  where "+
		"  r.isDelete = false ";
	    hql = addWhere3(vg, hql);
	 	List<SalelistItem>  grs =  salelistItemDao.find(hql);
	 	SalelistItem gr =  null;
	 	for(int i=0;i<grs.size();i++){
	 		gr = grs.get(i);
	 		if(gr.getGoods()!=null&&gr.getSalelist()!=null){
	 		GoodsRepertory ga = new GoodsRepertory();
	 		System.out.println(gr.getGoods().getId());
	 		ga.setGoods(new Goods(gr.getGoods().getId()));
	 		ga.setRepertory(new Repertory(gr.getSalelist().getRepertory().getId())) ;
	 		List<VOrderlistItem> vsi = orderServiceI.findByGoods(ga,"");
	 		for(int j=0;j<vsi.size();){
	 			VOrderlistItem voli = vsi.get(j);
	 			if(kc<=0){
	 				kc = gr.getNumber();
	 			}
	 			if(kc-voli.getNum()>0){
	 				cb += voli.getNum()*voli.getBuyPrice();
	 				kc = gr.getNumber()-voli.getNum();
	 				j++;
	 			}else{
	 				cb += kc*voli.getBuyPrice();
	 				kc = 0;
	 				break;
	 			}
	 		}
	 	}
	 	}
		return cb; 
	}*/


}
